/**
 * 
 */
package com.softwareinlife.xmpp.server.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.Subscription;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.softwareinlife.xmpp.server.data.PMF;
import com.softwareinlife.xmpp.server.model.JIDModel;
import com.softwareinlife.xmpp.server.util.JIDUtil;

/**
 * This XMPP bot JID is xmppsoftwareinlife@appspot.com
 * 
 * @author jangsunjin@softwareinlife.com
 * 
 */
@SuppressWarnings("serial")
public class XMPPSubscribeServlet extends HttpServlet {

	/**
	 * Logger
	 */
	public static final Logger log = Logger
			.getLogger(XMPPSubscribeServlet.class.getName());

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		log.log(Level.ALL, this.getClass().getName() + " is start!");
		
		try {
			// STEP 1
			XMPPService xmpp = XMPPServiceFactory.getXMPPService();
			Subscription sub = xmpp.parseSubscription(req);

			if (sub != null) {
				JIDModel model = JIDUtil.parseJID(sub.getFromJid());
				if (model != null) {
					PersistenceManager pm = PMF.getFactory()
							.getPersistenceManager();
					try {
						pm.makePersistent(model);
					} finally {
						pm.close();
					}
				}
			}
			
			xmpp.sendInvitation(sub.getFromJid());
		} catch (Exception e) {
			log.log(Level.SEVERE, e.getMessage());
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		
		try {
			// STEP 1
			XMPPService xmpp = XMPPServiceFactory.getXMPPService();
			Subscription sub = xmpp.parseSubscription(req);

			if (sub != null) {
				JIDModel model = JIDUtil.parseJID(sub.getFromJid());
				if (model != null) {
					PersistenceManager pm = PMF.getFactory()
							.getPersistenceManager();
					try {
						pm.makePersistent(model);
					} finally {
						pm.close();
					}
				}
			}
			
			xmpp.sendInvitation(sub.getFromJid());
		} catch (Exception e) {
			log.log(Level.SEVERE, e.getMessage());
		}
	}
}
